<template>
  <!-- 人员基础信息详情 -->
  <base-breadcrumb :title="$route.meta.title">
    <!-- 基础信息 -->
    <a-spin :spinning="loading">
      <a-card :bordered="false">
        <title-name title="基础信息"></title-name>
        <a-form-model
          ref="ruleForm"
          :model="form"
          :label-col="{ span: 6 }"
          :wrapper-col="{ span: 18 }"
          :rules="rules"
          style="position: relative"
        >
          <custom-form :formList="baseForm" :form="form" :editModel="editModel == 0 ? 'V' : 'E'">
            <!-- 个人照 -->
            <template #fileArrays>
              <span v-if="editModel == 0 && (!form.fileArrays || form.fileArrays.length < 1)" style="margin-top: -3px">
                无
              </span>
              <div v-else>
                <l-table
                  uploadType="image"
                  businessCode="PM28"
                  count="1"
                  :disabled="editModel == 0"
                  :editModel="editModel"
                  :uploadArrys.sync="form.fileArrays"
                  multiple
                ></l-table>
              </div>
            </template>
          </custom-form>
        </a-form-model>
      </a-card>
      <!-- 资格证书 -->
      <a-card :bordered="false" :style="[{ marginBottom: editModel != 2 ? '12px' : '50px' }]">
        <title-name title="资格证书"></title-name>
        <a-row type="flex" class="mb12" v-if="editModel != 0">
          <a-button class="mr20" type="primary" icon="plus" @click="handleManage(0)">新增资格证书</a-button>
        </a-row>
        <s-table
          bordered
          ref="table"
          size="default"
          rowKey="index"
          :columns="columns"
          :data="loadData"
          :showPagination="false"
        >
          <template slot="actions" slot-scope="text, record">
            <a @click="handleManage(1, record)">编辑</a>
          </template>
          <template slot="fileArrays" slot-scope="text, record">
            <file-link :fileList="record.fileArrays"></file-link>
          </template>
        </s-table>
      </a-card>
      <!-- 项目经历 -->
      <a-card v-if="editModel != 2" :bordered="false" style="margin-bottom: 50px">
        <title-name title="项目经历"></title-name>
        <s-table
          bordered
          ref="tableTwo"
          size="default"
          rowKey="index"
          :columns="columnsProject"
          :data="loadDataProject"
          :showPagination="false"
        >
        </s-table>
      </a-card>
    </a-spin>
    <!-- 页脚操作栏 -->
    <div
      class="btn_box page-btn-right-top"
      style="position: fixed; bottom: 0; right: 50px; height: 50px; display: flex; align-items: center; z-index: 99"
    >
      <a-button v-if="editModel != 0" type="primary" @click="handleSubmit" class="mr20" :loading="loading"
        >提交</a-button
      >
      <a-button type="primary" @click="handleActiveClose">关闭</a-button>
    </div>
    <!-- 表单弹窗 -->
    <dialog-form
      ref="dialogForm"
      :visible.sync="visible"
      editModel="E"
      :form="forms"
      :forms.sync="forms"
      :headerTitle="`${['新增', '编辑'][editModelTwo]}资格证书`"
      :width="1000"
      :formList="formList"
      :rules="rulesTwo"
      @confirm="handleConfirm"
    >
      <!-- 附件上传 -->
      <template v-if="visible" #fileArrays>
        <l-table businessCode="PM28" :uploadArrys.sync="forms.fileArrays"></l-table>
      </template>
    </dialog-form>
  </base-breadcrumb>
</template>

<script>
import { STable, Ellipsis } from '@/components'
import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
import DialogForm from '@/components/DialogForm' // 表单弹窗
import Selector from '@/components/Select/Selector' // 下拉框
import { createValidator, idCard, isPhone } from '@/utils/regExpression' // 正则校验
import { getPersonDetail, addPerson, editPerson, addCertificates, editCertificates } from '@/api/project/projects' // api

const columnsProject = [
  {
    title: '序号',
    dataIndex: 'index',
    width: 100,
    customRender() {
      return arguments[2] + 1
    },
  },
  {
    title: '分公司',
    dataIndex: 'branchComName',
    ellipsis: true,
  },
  {
    title: '项目',
    dataIndex: 'projectName',
    ellipsis: true,
  },

  {
    title: '分包',
    ellipsis: true,
    dataIndex: 'subContractorName',
  },
  {
    title: '班组',
    ellipsis: true,
    dataIndex: 'headmasterName',
  },
  {
    title: '工种',
    dataIndex: 'workTypeName',
    ellipsis: true,
  },
  {
    title: '进场时间',
    dataIndex: 'approachDate',
    width: 150,
  },
  {
    title: '出场时间',
    dataIndex: 'outDate',
    width: 150,
  },
  {
    title: '状态',
    dataIndex: 'statusName',
    width: 100,
  },
]

export default {
  extends: new BaseEditPage(),
  name: 'personManageEdit',
  components: {
    STable,
    DialogForm,
  },
  data() {
    return {
      columnsProject, // 项目经历表头
      loading: false,
      form: {
        whetherSpecialType: '0',
        // idCard: '513022199407151516',
        // phone: '18878987676',
        // name: '懂非',
        // sex: '0',
      }, // 表单
      forms: {}, // 弹窗表单
      editModel: 2, // 页面操作类型：0 查看；1 编辑；2 添加
      editModelTwo: 2, // 弹窗操作类型：0 查看；1 编辑；2 添加
      visible: false, // 弹窗显隐控件
      loadData: () => {
        return new Promise((resolve) => {
          resolve({
            data: this.certificates,
          })
        })
      }, // 资格证书表格
      loadDataProject: () => {
        return new Promise((resolve) => {
          resolve({
            data: this.projectExperiences,
          })
        })
      }, // 项目表格
      formList: [
        {
          type: 'BaseInput',
          keyName: 'name',
          label: '证书名称',
          span: 12,
        },
        {
          type: 'BaseInput',
          keyName: 'number',
          label: '证书编号',
          span: 12,
        },
        {
          type: Selector,
          keyName: 'certificatesType',
          label: '证书类型',
          span: 12,
          attrs: {
            selectType: '35',
            urlType: 'project',
            labelInValue: true,
          },
        },
        {
          type: Selector,
          keyName: 'certificatesLevel',
          label: '证书等级',
          span: 12,
          attrs: {
            selectType: '36',
            urlType: 'project',
            labelInValue: true,
          },
        },
        {
          type: 'a-date-picker',
          keyName: 'startTermOfValidity',
          label: '有效时间（起）',
          span: 12,
          attrs: {
            valueFormat: 'YYYY-MM-DD',
            disabledDate: (current) => {
              // Can not select days before today and today
              return (
                this.forms.endTermOfValidity &&
                current &&
                current > this.moment(this.forms.endTermOfValidity).startOf('day')
              )
            },
          },
        },
        {
          type: 'a-date-picker',
          keyName: 'endTermOfValidity',
          label: '有效时间（止）',
          span: 12,
          attrs: {
            valueFormat: 'YYYY-MM-DD',
            disabledDate: (current) => {
              // Can not select days before today and today
              return (
                this.forms.startTermOfValidity &&
                current &&
                current < this.moment(this.forms.startTermOfValidity).endOf('day')
              )
            },
          },
        },
        {
          slot: true,
          keyName: 'fileArrays',
          label: '上传证书',
          span: 24,
        },
      ], // 资格证书表单列表
      rules: {
        idCard: [
          { required: true, validator: createValidator(idCard, '请输入正确的身份证号码', true), trigger: 'blur' },
        ],
        name: [{ required: true, whitespace: true, message: '请输入姓名', trigger: 'change' }],
        sex: [{ required: true, message: '请选择性别', trigger: 'change' }],
        phone: [{ required: true, validator: createValidator(isPhone, '请输入正确的手机号码', true), trigger: 'blur' }],
        fileArrays: [{ type: 'array', required: true, message: '请上传个人照', trigger: 'blur' }],
      }, // 表单校验
      rulesTwo: {
        name: [{ required: true, whitespace: true, message: '请输入证书名称', trigger: 'change' }],
        number: [{ required: true, whitespace: true, message: '请输入证书编号', trigger: 'change' }],
        certificatesType: [{ required: true, message: '请选择证书类型', trigger: 'blur' }],
        certificatesLevel: [{ required: true, message: '请选择证书等级', trigger: 'change' }],
        startTermOfValidity: [{ required: true, message: '请选择有效时间（起）', trigger: 'change' }],
        endTermOfValidity: [{ required: true, message: '请选择有效时间（止）', trigger: 'change' }],
        fileArrays: [{ type: 'array', required: true, message: '请上传证书', trigger: 'blur' }],
      }, // 弹窗表单校验
      certificates: [], // 资格证书列表
      projectExperiences: [], // 项目经历列表
      init: false, // 初始化标志
    }
  },
  computed: {
    // 资格证书表头
    columns() {
      const columns = [
        {
          title: '序号',
          dataIndex: 'index',
          width: 100,
          customRender() {
            return arguments[2] + 1
          },
        },
        {
          title: '证书类型',
          dataIndex: 'certificatesType.label',
          ellipsis: true,
        },
        {
          title: '证书名称',
          dataIndex: 'name',
          ellipsis: true,
        },

        {
          title: '证书编号',
          dataIndex: 'number',
        },
        {
          title: '有效期',
          dataIndex: 'time',
          customRender(text, record) {
            return record.startTermOfValidity + '~' + record.endTermOfValidity
          },
        },
        {
          title: '证书等级',
          dataIndex: 'certificatesLevel.label',
          ellipsis: true,
        },
        {
          title: '附件',
          dataIndex: 'fileArrays',
          scopedSlots: { customRender: 'fileArrays' },
        },
      ]
      // 若不为查看，则加上操作
      if (this.editModel != 0) {
        columns.push({
          title: '操作',
          dataIndex: 'actions',
          width: 150,
          scopedSlots: { customRender: 'actions' },
        })
      }
      return columns
    },
    // 管理人员表单列表
    baseForm() {
      return [
        {
          keyName: 'name',
          type: 'BaseInput',
          disabled: this.editModel == 0,
          label: '姓名',
        },
        {
          keyName: 'sex',
          viewName: 'sexName',
          type: 'a-select',
          disabled: this.editModel == 0,
          label: '性别',
          data: [
            {
              value: '0',
              label: '女',
            },
            {
              value: '1',
              label: '男',
            },
          ],
        },
        {
          keyName: 'birthday',
          type: 'BaseInput',
          disabled: this.editModel == 0,
          hidden: this.editModel != 0,
          label: '出生年月',
        },
        {
          keyName: 'idCard',
          type: 'BaseInput',
          disabled: this.editModel == 0,
          label: '身份证号码',
        },
        {
          keyName: 'phone',
          type: 'BaseInput',
          disabled: this.editModel == 0,
          label: '电话号码',
        },
        {
          keyName: 'whetherSpecialType',
          viewName: 'whetherSpecialTypeName',
          type: 'a-select',
          disabled: true,
          label: '是否为特种作业人员',
          data: [
            {
              label: '否',
              value: '0',
            },
            {
              label: '是',
              value: '1',
            },
          ],
        },
        {
          keyName: 'specialTypeName',
          disabled: true,
          placeholder: '请添加特种作业证书',
          type: 'BaseInput',
          label: '特种作业证书名称',
        },
        {
          keyName: 'fileArrays',
          slot: true,
          label: '个人照',
          span: 24,
        },
      ]
    },
  },
  mounted() {
    this.$route.meta.title = ['人员基础信息详情', '人员基础信息编辑', '人员基础信息新增'][this.editModel]
    // 获取详情
    if (this.editModel != 2) {
      this.loading = true
      getPersonDetail({ id: this.businessId || this.id })
        .then((res) => {
          this.loading = false
          // 格式化证书列表
          res.data.certificates.forEach((item) => {
            item.certificatesType = { key: item.certificatesTypeId, label: item.certificatesTypeName }
            item.certificatesLevel = { key: item.certificatesLevelId, label: item.certificatesLevelName }
          })
          this.form = res.data
          this.projectExperiences = res.data.projectExperiences
          this.certificates = res.data.certificates
          this.$refs.table.refresh(true)
          this.$refs.tableTwo.refresh(true)
          this.$nextTick(() => {
            this.init = true
          })
        })
        .catch(() => {
          this.loading = false
        })
    } else {
      this.$nextTick(() => {
        this.init = true
      })
    }
  },
  watch: {
    // 监听证书列表
    certificates(e) {
      if (e.length > 0) {
        this.$set(this.form, 'whetherSpecialType', '1')
        this.$set(this.form, 'specialTypeName', e[0].name)
      } else {
        this.$set(this.form, 'whetherSpecialType', '0')
        this.$set(this.form, 'specialTypeName', '')
      }
    },
    'form.fileArrays'(e) {
      if (this.editModel != 0 && this.init) {
        this.$nextTick(() => {
          this.$refs.ruleForm?.validateField('fileArrays')
        })
      }
    },
    'forms.fileArrays'(e) {
      this.$nextTick(() => {
        this.$refs.dialogForm.$refs.ruleForm?.validateField('fileArrays')
      })
    },
  },
  methods: {
    /**
     * 添加或编辑操作；type操作类型：type: 0 添加，1 编辑；record：编辑项
     */
    handleManage(type, record) {
      this.editModelTwo = type
      this.forms = record || {}
      record && (this.forms.defaultNumber = record.number)
      this.visible = true
    },
    /**
     * 提交弹窗表单
     */
    handleConfirm(e) {
      if (this.editModel == 2) {
        if (this.editModelTwo == 0) {
          for (let item of this.certificates) {
            if (item.number === e.number) {
              this.$message.warning('此证书编号列表已存在！')
              return
            }
          }
          this.certificates.push(e)
          this.$refs.table.refresh(true)
        } else {
          for (let index in this.certificates) {
            let item = this.certificates[index]
            if (item.number === e.defaultNumber) {
              this.$set(this.certificates, index, e)
              item = e
            } else if (item.number === e.number) {
              this.$message.warning('此证书编号列表已存在！')
              return
            }
          }
          this.$refs.table.refresh(true)
        }
        this.visible = false
      } else {
        let api = [addCertificates, editCertificates][this.editModelTwo]
        this.$refs.dialogForm.loading = true
        // 格式化证书列表
        e.certificatesTypeId = e.certificatesType.key
        e.certificatesLevelId = e.certificatesLevel.key
        e.personnelId = this.id
        api(e)
          .then((res) => {
            this.$refs.dialogForm.loading = false
            this.$message.success(`${['添加', '编辑'][this.editModelTwo]}成功`)
            this.visible = false
            this.getCertificates()
          })
          .catch((res) => {
            this.$refs.dialogForm.loading = false
          })
      }
    },
    /**
     * 获取证书
     */
    getCertificates() {
      this.$refs.table.localLoading = true
      getPersonDetail({ id: this.businessId || this.id })
        .then((res) => {
          this.$refs.table.localLoading = false
          // 格式化证书列表
          res.data.certificates.forEach((item) => {
            item.certificatesType = { key: item.certificatesTypeId, label: item.certificatesTypeName }
            item.certificatesLevel = { key: item.certificatesLevelId, label: item.certificatesLevelName }
          })
          this.certificates = res.data.certificates
          this.$refs.table.refresh(true)
        })
        .catch((res) => {
          this.$refs.table.localLoading = false
        })
    },
    /**
     * 提交表单
     */
    handleSubmit() {
      let api = [editPerson, addPerson][this.editModel - 1]
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.loading = true
          // 格式化证书列表
          if (this.editModel == 2) {
            this.certificates.forEach((item) => {
              item.certificatesTypeId = item.certificatesType.key
              item.certificatesLevelId = item.certificatesLevel.key
            })
            this.form.certificates = this.certificates
          }
          api(this.form)
            .then((res) => {
              this.loading = false
              this.$message.success(`${['编辑', '添加'][this.editModel - 1]}成功`)
              this.handleActiveClose()
            })
            .catch((res) => {
              this.loading = false
            })
        }
      })
    },
  },
}
</script>